<?php
require_once 'config.php';
require_once 'db_manager.php';
require_once 'api_manager.php';
session_start();

$result = null;
$error = null;

// 获取查询历史
if (isset($_SESSION['user_id'])) {
    $db = DBManager::getInstance();
    $conn = $db->getConnection();
    $stmt = $conn->prepare("SELECT * FROM tracking_history WHERE user_id = ? ORDER BY query_time DESC LIMIT 10");
    $stmt->bind_param("i", $_SESSION['user_id']);
    $stmt->execute();
    $history = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
}

// 支持通过GET参数自动查询
if (empty($_POST) && isset($_GET['tracking_number'])) {
    $_POST['tracking_number'] = $_GET['tracking_number'];
    if (isset($_GET['carrier'])) {
        $_POST['carrier'] = $_GET['carrier'];
    }
    $_SERVER['REQUEST_METHOD'] = 'POST';
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $tracking_number = $_POST['tracking_number'];
    $carrier = isset($_POST['carrier']) ? $_POST['carrier'] : '';
    
    try {
        // 使用API管理类查询快递
        $api = APIManager::getInstance();
        $result = $api->queryExpress($tracking_number, $carrier);
        
        // 获取最新状态
        $latest_status = '';
        if (isset($result['result']['list'][0]['status'])) {
            $latest_status = $result['result']['list'][0]['status'];
        }
        
        // 如果用户已登录，更新查询记录
        if (isset($_SESSION['user_id'])) {
            $db = DBManager::getInstance();
            $conn = $db->getConnection();
            
            // 检查是否已存在该单号的记录
            $stmt = $conn->prepare("SELECT id FROM tracking_history WHERE user_id = ? AND tracking_number = ?");
            $stmt->bind_param("is", $_SESSION['user_id'], $tracking_number);
            $stmt->execute();
            $existing = $stmt->get_result()->fetch_assoc();
            $stmt->close();
            
            if ($existing) {
                // 更新现有记录
                $stmt = $conn->prepare("UPDATE tracking_history SET carrier = ?, status = ?, query_time = CURRENT_TIMESTAMP WHERE id = ?");
                $stmt->bind_param("ssi", $carrier, $latest_status, $existing['id']);
            } else {
                // 插入新记录
                $stmt = $conn->prepare("INSERT INTO tracking_history (user_id, tracking_number, carrier, status) VALUES (?, ?, ?, ?)");
                $stmt->bind_param("isss", $_SESSION['user_id'], $tracking_number, $carrier, $latest_status);
            }
            $stmt->execute();
            $stmt->close();
            
            // 重新获取查询历史
            $stmt = $conn->prepare("SELECT * FROM tracking_history WHERE user_id = ? ORDER BY query_time DESC LIMIT 10");
            $stmt->bind_param("i", $_SESSION['user_id']);
            $stmt->execute();
            $history = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
        }
    } catch (Exception $e) {
        $error = "查询失败：" . $e->getMessage();
    }
}
?>

<style>
.table th {
    text-align: center;
    vertical-align: middle;
    font-size: 1rem;
}
.table td {
    font-size: 0.85rem;
    vertical-align: middle;
}
/* 仅对历史列表状态列做截断，查询结果表格不做截断 */
.history-status {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 220px;
}
.table-hover tbody tr {
    cursor: pointer;
    transition: background 0.2s;
}
.table-hover tbody tr:hover {
    background: #f0f4ff;
}
/* 顺丰弹窗样式 */
#sf-modal-bg {
    position: fixed;
    left: 0; top: 0; right: 0; bottom: 0;
    background: rgba(0,0,0,0.3);
    z-index: 2000;
    display: none;
}
#sf-modal {
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 16px rgba(0,0,0,0.2);
    padding: 2rem 1.5rem 1.5rem 1.5rem;
    z-index: 2100;
    min-width: 260px;
    max-width: 90vw;
    display: none;
}
#sf-modal input {
    text-align: center;
    font-size: 1.2rem;
    letter-spacing: 0.2em;
}
</style>

<?php include 'header.php'; ?>

<div class="row justify-content-center">
    <div class="col-md-8">
        <div class="card">
            <div class="card-header">
                <h3 class="text-center">快递查询</h3>
            </div>
            <div class="card-body">
                <form method="POST" action="" id="queryForm" autocomplete="off">
                    <div class="mb-3">
                        <label for="tracking_number" class="form-label">快递单号</label>
                        <input type="text" class="form-control" id="tracking_number" name="tracking_number" required autocomplete="off">
                    </div>
                    <div class="mb-3">
                        <label for="carrier" class="form-label">快递公司（可选）</label>
                        <select class="form-select" id="carrier" name="carrier">
                            <option value="">自动识别</option>
                            <option value="zto">中通快递</option>
                            <option value="sto">申通快递</option>
                            <option value="yto">圆通快递</option>
                            <option value="yd">韵达快递</option>
                            <option value="sf">顺丰快递</option>
                            <option value="ems">EMS</option>
                        </select>
                        <div class="form-text">如果不选择快递公司，系统将自动识别</div>
                    </div>
                    <div class="d-grid">
                        <button type="submit" class="btn btn-primary">查询</button>
                    </div>
                </form>
                
                <?php if(isset($error)): ?>
                    <div class="alert alert-danger mt-3"><?php echo $error; ?></div>
                <?php endif; ?>
                
                <?php if(isset($result)): ?>
                    <div class="mt-4">
                        <h4>查询结果</h4>
                        <?php if(isset($result['result']['com'])): ?>
                            <div class="alert alert-info">
                                识别到的快递公司：<?php echo $result['result']['com']; ?>
                            </div>
                        <?php endif; ?>
                        <div class="table-responsive">
                            <table class="table table-striped mb-0">
                                <thead>
                                    <tr>
                                        <th>时间</th>
                                        <th>状态</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if(isset($result['result']['list']) && is_array($result['result']['list'])): ?>
                                        <?php foreach($result['result']['list'] as $item): ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($item['time']); ?></td>
                                                <td><?php echo htmlspecialchars($item['status']); ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="2" class="text-center">暂无物流信息</td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                <?php endif; ?>
                
                <?php if(isset($_SESSION['user_id']) && !empty($history)): ?>
                    <div class="mt-4">
                        <h4>最近查询</h4>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>单号</th>
                                        <th>状态</th>
                                        <th>查询时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach($history as $item): ?>
                                        <tr onclick="window.location.href='index.php?tracking_number=<?php echo $item['tracking_number']; ?><?php if(!empty($item['carrier'])) echo '&carrier=' . urlencode($item['carrier']); ?>'">
                                            <td><?php echo explode(':', $item['tracking_number'])[0]; ?></td>
                                            <td class="history-status">
                                                <?php 
                                                $status = isset($item['status']) ? (string)$item['status'] : '暂无状态';
                                                if (mb_strlen($status, 'UTF-8') > 20) {
                                                    echo mb_substr($status, 0, 20, 'UTF-8') . '...';
                                                } else {
                                                    echo $status;
                                                }
                                                ?>
                                            </td>
                                            <td><?php echo $item['query_time']; ?></td>
                                            <td>
                                                <a href="history.php?delete=<?php echo $item['id']; ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('确定要删除这条记录吗？')">删除</a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- 顺丰弹窗 -->
<div id="sf-modal-bg"></div>
<div id="sf-modal">
    <div class="mb-3 text-center">
        <strong>顺丰快递需要输入手机号后四位</strong>
    </div>
    <input type="text" id="sf-phone" maxlength="4" class="form-control mb-3" placeholder="请输入手机号后四位">
    <div class="d-grid">
        <button class="btn btn-primary" id="sf-confirm">确定</button>
    </div>
</div>
<script>
const form = document.getElementById('queryForm');
const carrierSelect = document.getElementById('carrier');
const trackingInput = document.getElementById('tracking_number');
const sfModalBg = document.getElementById('sf-modal-bg');
const sfModal = document.getElementById('sf-modal');
const sfPhone = document.getElementById('sf-phone');
const sfConfirm = document.getElementById('sf-confirm');
let sfRequired = false;
let sfPhoneValue = '';

function isSF(tracking, carrier) {
    return carrier === 'sf' || (carrier === '' && /^SF\d+/i.test(tracking));
}

function showSFModal() {
    sfModalBg.style.display = 'block';
    sfModal.style.display = 'block';
    sfPhone.value = '';
    sfPhone.focus();
}
function hideSFModal() {
    sfModalBg.style.display = 'none';
    sfModal.style.display = 'none';
}

// 监听单号和快递公司输入，自动弹窗
trackingInput.addEventListener('blur', function() {
    const tracking = trackingInput.value.trim();
    const carrier = carrierSelect.value;
    if (isSF(tracking, carrier) && !sfRequired) {
        sfRequired = true;
        showSFModal();
    }
});
carrierSelect.addEventListener('change', function() {
    const tracking = trackingInput.value.trim();
    const carrier = carrierSelect.value;
    if (isSF(tracking, carrier) && !sfRequired) {
        sfRequired = true;
        showSFModal();
    }
});

sfConfirm.onclick = function() {
    const phone = sfPhone.value.trim();
    if (!/^\d{4}$/.test(phone)) {
        sfPhone.classList.add('is-invalid');
        sfPhone.focus();
        return;
    }
    sfPhone.classList.remove('is-invalid');
    sfPhoneValue = phone;
    hideSFModal();
    // 触发表单提交
    form.requestSubmit();
};
// 点击遮罩关闭弹窗
sfModalBg.onclick = function() {
    hideSFModal();
};

// 表单提交时，顺丰自动拼接后四位，提交后还原
form.addEventListener('submit', function(e) {
    const tracking = trackingInput.value.trim();
    const carrier = carrierSelect.value;
    if (isSF(tracking, carrier)) {
        if (!sfPhoneValue) {
            // 没有输入后四位，弹窗
            e.preventDefault();
            showSFModal();
            return;
        }
        // 拼接后四位，提交
        trackingInput.value = tracking + ':' + sfPhoneValue;
        setTimeout(() => {
            trackingInput.value = tracking; // 提交后还原
            sfPhoneValue = '';
            sfRequired = false;
        }, 100);
    } else {
        sfPhoneValue = '';
        sfRequired = false;
    }
});
</script>

<?php include 'footer.php'; ?> 